package com.lst.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.dao.MstCodeMapper;
import com.lst.dao.VideoInfoMapper;
import com.lst.entity.request.VideoReqPara;
import com.lst.entity.response.VideoResPara;
import com.lst.model.ClientNum;
import com.lst.model.MstCode;
import com.lst.model.VideoInfo;
import com.lst.service.ClientNumService;
import com.lst.service.MstDiscussService;
import com.lst.utils.CommFunUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

public class VideoDetailServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;

	private VideoInfoMapper videoInfoMapper = ctx.getBean(VideoInfoMapper.class);

	private ClientNumService clientNumService = ctx.getBean(ClientNumService.class);

	private MstDiscussService mstDiscussService = ctx.getBean(MstDiscussService.class);

	private MstCodeMapper mstCodeMapper = ctx.getBean(MstCodeMapper.class);

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);

		VideoResPara resPara = new VideoResPara();
		try {
			VideoReqPara reqPara = getReqPara(request);

			if (isCheckField(reqPara, resPara)) {
				Integer viid = Integer.valueOf(reqPara.getViid());
				String userid = reqPara.getUserid();

				VideoInfo vi = videoInfoMapper.selectByPrimaryKey(viid);				
                 if(vi!=null){
                	//视频类型
     				MstCode mc = mstCodeMapper.selectByPrimaryKey(vi.getVitype());					
     				vi.setVitypename(mc.getName());

     				//收藏量
     				Integer favoritenum = CommFunUtils.opNum(null, vi.getId(), CommCode.SYSTEM_CARESEL_RANGE_VIDEO, CommCode.SYSTEM_COUNT_FAVORITE, clientNumService);
     				//分享量
     				Integer sharenum = CommFunUtils.opNum(null, vi.getId(), CommCode.SYSTEM_CARESEL_RANGE_VIDEO, CommCode.SYSTEM_COUNT_SHARE, clientNumService);
     				//浏览量
     				Map<String, Object> videomap = new HashMap<String, Object>();

     				videomap.put("enabled", true);
     				videomap.put("isDeleted", false);	
     				videomap.put("numtype", CommCode.SYSTEM_COUNT_BROWSE);
     				videomap.put("actid", viid);
     				videomap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_VIDEO);

     				List<ClientNum> browselist = clientNumService.queryByList(videomap);

     				Integer browsenum = 0;

     				for(ClientNum c : browselist){
     					browsenum += c.getNum() == null ? 0 : c.getNum();
     				}

     				vi.setFavoritenum(favoritenum);
     				vi.setSharenum(sharenum);
     				vi.setBrowsenum(browsenum);

     				//评论量
     				videomap.clear();
     				videomap.put("enabled", true);
     				videomap.put("isDeleted", false);
     				videomap.put("tarid", viid);
     				videomap.put("type", CommCode.SYSTEM_CARESEL_RANGE_VIDEO);

     				Integer discussnum = mstDiscussService.queryCountByMap(videomap);

     				vi.setVideodiscussnum(discussnum);

     				List<ClientNum> cns = null;//统计量
     				if(!StringUtils.isEmpty(userid)){
     					videomap.clear();
     					videomap.put("enabled", true);
     					videomap.put("isDeleted", false);
     					videomap.put("numtype",CommCode.SYSTEM_COUNT_FAVORITE);
     					videomap.put("clientid", Integer.valueOf(userid));
     					videomap.put("actid", viid);
     					videomap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_VIDEO);

     					cns = clientNumService.queryByList(videomap);//查询统计量
     				}

     				if(null==cns||cns.size()==0){
     					vi.setIsFavorite(false);
     				}else{					
     					vi.setIsFavorite(true);						
     				}
     				//格式化时间
     				String videotime = DateUtil.getFormatTime(vi.getCreatedate(), DateUtil.ALL_DATETIME_SEPARATOR_SPOT);
     				vi.setVideotime(videotime);	

     				resPara.setVideoinfo(vi);
     				resPara.setCode(CommCode.M_Y000000);
     				resPara.setMessage(CommCode.M_Y000001);	
                 }else{
                	resPara.setCode(CommCode.M_A000001);
                	resPara.setMessage(CommCode.M_A000002);
                 }
							

			}
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
			logger.info(jsonResult);

			logger.info("VideoDetailServlet jsonResult: " + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public VideoReqPara getReqPara(HttpServletRequest request) {

		VideoReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request,new VideoReqPara());

			reqPara = (VideoReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String viid = request.getParameter("viid");

			logger.info("reqPara userid: " + userid);
			logger.info("reqPara viid: " + viid);

			reqPara.setUserid(userid);
			reqPara.setViid(viid);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}
		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		VideoReqPara ocReqPara = (VideoReqPara) reqPara;
		VideoResPara ocResPara = (VideoResPara) resPara;

		if (StringUtils.isEmpty(ocReqPara.getViid())) {
			ocResPara.setCode(CommCode.M_A000000);
			ocResPara.setMessage(CommCode.M_E000030);
		} else {
			flag = true;
		}
		return flag;
	}
}
